import 'package:flutter/material.dart';
import '../model/post.dart';
import '../model/product.dart';
import '../repository/post_repository.dart';
// 产品标签页
class PostTab extends StatefulWidget {
  final PostRepository postRepo;

  const PostTab({Key? key, required this.postRepo}) : super(key: key);

  @override
  _PostTabState createState() => _PostTabState();
}

class _PostTabState extends State<PostTab> {
  int _page = 1;
  final int _perPage = 10;
  List<Post> _posts = [];
  int _total = 0;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadProducts();
  }

  Future<void> _loadProducts() async {
    setState(() => _isLoading = true);

    final response = await widget.postRepo.getPosts();

    if (response.data != null) {
      setState(() {
        _posts = response.data!;
        // _total = response.data!.total;
        _isLoading = false;
      });
    } else {
      setState(() {
        _isLoading = false;
        print("product 加载失败: ${response.message}");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: ${response.message}')),
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            itemCount: _posts.length,
            itemBuilder: (context, index) {
              final post = _posts[index];
              return ListTile(
                title: Text(post.title),
                subtitle: Text('\$${post.body}'),
              );
            },
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                icon: const Icon(Icons.arrow_back),
                onPressed: _page > 1 ? () {
                  setState(() => _page--);
                  _loadProducts();
                } : null,
              ),
              Text('第 $_page 页，共 ${(_total / _perPage).ceil()} 页'),
              IconButton(
                icon: const Icon(Icons.arrow_forward),
                onPressed: _page < (_total / _perPage).ceil() ? () {
                  setState(() => _page++);
                  _loadProducts();
                } : null,
              ),
            ],
          ),
        ),
      ],
    );
  }
}